package hhm.spring.security;

import com.alibaba.fastjson.JSON;
import hhm.spring.pojo.HHMResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authentication)
			throws IOException, ServletException {
		HttpSession session = request.getSession();

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");

		HHMResponse hhmResponse = new HHMResponse();
		if (authentication instanceof UsernameNotFoundException) {
			hhmResponse.setSuccess(false).setMsg(
					authentication.getLocalizedMessage());
		} else if(authentication instanceof BadCredentialsException) {
			hhmResponse.setSuccess(false).setMsg("密码错误");
		}else{
			hhmResponse.setSuccess(false).setMsg(
					authentication.getLocalizedMessage());
		}

		response.getWriter().println(JSON.toJSON(hhmResponse));
		response.getWriter().flush();

	}
}
